package system

import (
	"faker/project-public/common/response"
	"faker/project-public/global"
	sysResponse "faker/project-public/model/response"
	"faker/project-public/model/sys"
	"faker/project-public/request"
	"faker/project-public/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type SysLoginApi struct {
}

func (b *SysLoginApi) Login(c *gin.Context) {
	var l request.Login
	err := c.ShouldBindJSON(&l)

	if err != nil {
		response.ErrorWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(l, utils.LoginVerify)
	if err != nil {
		response.ErrorWithMessage(err.Error(), c)
		return
	}
	userData := &sys.SysUser{Username: l.Username, PasswordHash: l.PasswordHash}
	user, err := userService.Login(*userData)
	if err != nil {
		global.FAKER_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
		// 验证码次数+1
		response.ErrorWithMessage("用户名不存在或者密码错误", c)
		return
	}
	if user.Status != 1 {
		global.FAKER_LOG.Error("登陆失败! 用户被禁止登录!")
		response.ErrorWithMessage("用户被禁止登录", c)
		return
	}
	b.TokenNext(c, *user)
	return
}

// TokenNext 登录以后签发jwt
func (b *SysLoginApi) TokenNext(c *gin.Context, user sys.SysUser) {
	j := &utils.JWT{SigningKey: []byte(global.FAKER_CONFIG.JWT.SigningKey)} // 唯一签名
	claims := j.CreateClaims(request.BaseClaims{
		ID:       user.ID,
		Name:     user.Name,
		Username: user.Username,
		RoleId:   uint(user.RoleId),
	})
	token, err := j.CreateToken(claims)
	if err != nil {
		global.FAKER_LOG.Error("获取token失败!", zap.Error(err))
		response.ErrorWithMessage("获取token失败", c)
		return
	}
	response.SuccessWithDetailed(sysResponse.LoginResponse{
		User:      user,
		Token:     token,
		ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
	}, "登录成功", c)
}

// Logout 退出登录  这里后面记录日志就行
func (b *SysLoginApi) Logout(c *gin.Context) {
	response.SuccessWithMessage("退出登录成功", c)
}
